package com.quan.site.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.quan.commons.core.MyBaseServiceImpl;
import com.quan.commons.utils.PageUtils;
import com.quan.site.commons.vo.SiteProductVo;
import com.quan.site.entity.SiteProduct;
import com.quan.site.entity.SiteProductCate;
import com.quan.site.mapper.SiteProductMapper;
import com.quan.site.service.SiteProductCateService;
import com.quan.site.service.SiteProductService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@Service
public class SiteProductServiceImpl extends MyBaseServiceImpl<SiteProductMapper, SiteProduct> implements SiteProductService {

    @Autowired
    private SiteProductMapper mapper;

    @Autowired
    private SiteProductCateService cateService;

    @Override
    public List<SiteProductVo> queryList(PageUtils pageUtils, SiteProductVo vo) {
        QueryWrapper<SiteProduct> queryWrapper = new QueryWrapper<SiteProduct>(vo);

        List<SiteProduct> list = super.list(pageUtils, queryWrapper);
        List<SiteProductVo> collect = list.stream().map(item -> {
            SiteProductVo bean = new SiteProductVo();
            BeanUtils.copyProperties(item, bean);
            return bean;
        }).collect(Collectors.toList());

        return collect;
    }

    @Override
    public PageUtils queryPage(PageUtils pageUtils, SiteProductVo vo) {
        QueryWrapper<SiteProduct> queryWrapper = new QueryWrapper<SiteProduct>(vo);

        if (StringUtils.isNotBlank(vo.getKeyword())) {
            queryWrapper.and(w -> {
                w.like("title", vo.getKeyword());
            });
        }

        final IPage<SiteProduct> page = super.selectPage(pageUtils, queryWrapper);

        PageUtils ps = new PageUtils(page);

        final List<SiteProduct> records = page.getRecords();

        final List<SiteProduct> collect = records.stream().map((item) -> {
            SiteProductVo bean = new SiteProductVo();
            BeanUtils.copyProperties(item, bean);

            // 取得所属分类
            if (item.getCate() != null) {
                final SiteProductCate cate = this.cateService.getById(item.getCate());
                bean.setCateName(cate.getName());
            }

            return bean;
        }).collect(Collectors.toList());

        ps.setRecords(collect);
        return ps;
    }
}